package com.sharemedia.managers.db
{
	import com.sharemedia.interfaces.IDBCommand;
	import com.sharemedia.vos.ServerTrack;
	
	import flash.data.SQLConnection;
	import flash.data.SQLResult;
	import flash.data.SQLStatement;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.SQLErrorEvent;
	import flash.events.SQLEvent;
	import flash.filesystem.File;
	
	public class TrackDataBase extends EventDispatcher
	{
		private const TRACKS_TABLE:String = "CREATE TABLE IF NOT EXISTS tracks (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
			"uid TEXT, fileName TEXT, songName TEXT, artist TEXT, length NUMBER, path TEXT, likeNum NUMBER, unlikeNum NUMBER)";
		
		private var connected:Boolean;
		
		public function TrackDataBase()
		{
			if(instance)
				throw Error("Only one instance allowed");
			
			connect();
		}
		
		private static var instance:TrackDataBase;
		public static function getInstance():TrackDataBase
		{
			if(!instance)
				instance = new TrackDataBase();
			
			return instance;
		}
		
		private var connection:SQLConnection;
		
		private var commands:Vector.<IDBCommand> = new Vector.<IDBCommand>();
		
		public function execute(command:IDBCommand):void
		{
			if(connected)
				command.execute(connection);
			else
				commands.push(command);
		}
		
		private function connect():void
		{
			var dbFile:File = File.applicationDirectory.resolvePath("SharedAudioMedia.sqlite");
			connection = new SQLConnection();          
			connection.addEventListener(SQLErrorEvent.ERROR, errorHandler);   
			connection.addEventListener(SQLEvent.OPEN, openHandler);          
			connection.open(dbFile);   
		}
		
		
		
		/**
		 */
		private function errorHandler(e:SQLErrorEvent):void
		{
			connected = false;
		}
		
		/**
		 */
		private function openHandler(e:SQLEvent):void
		{
			var statement:SQLStatement = new SQLStatement();          
			statement.sqlConnection = connection;                   
			statement.text = TRACKS_TABLE;                           
			statement.addEventListener(SQLErrorEvent.ERROR, errorHandler); 
			statement.addEventListener(SQLEvent.RESULT, createTableResult); 
			statement.execute();                                      
		}
		
		/**
		 */
		private function createTableResult(e:SQLEvent):void
		{
			connected = true;
			for each (var command:IDBCommand in commands) 
			{
				execute(command);				
			}
			
			commands.length = 0;
		}
	}
}